package com.cjx.stars.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cjx.stars.mapper.TeamMapper;
import com.cjx.stars.mapper.UserTeamMapper;
import com.cjx.stars.pojo.table.Team;
import com.cjx.stars.pojo.table.UserTeam;
import lombok.extern.log4j.Log4j2;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author cjx
 * @description 每天0点清理过期团队
 * @createDate 2024/3/29 18:18
 **/
@Component
@Log4j2
public class DeleteExpiredTeamTask {

    @Resource
    private  TeamMapper teamMapper;
    @Resource
    private UserTeamMapper userTeamMapper;
    @Resource
    private RedissonClient redissonClient;

    @Scheduled(cron = "0 0 0 * * ?")
    public void removeExpiredTeam() {

        RLock lock = redissonClient.getLock("removeExpiredTeam");
        try {
            if (lock.tryLock()){
                log.info("删除过期队伍方法开始执行了……");
                //1.查询所有过期队伍id
                LambdaQueryWrapper<Team> teamWrapper = new LambdaQueryWrapper<>();
                teamWrapper.lt(Team::getExpireTime, LocalDateTime.now()).select(Team::getId);
                List<Object> list = teamMapper.selectObjs(teamWrapper);
                if (list == null || list.isEmpty()){
                    log.info("无过期队伍");
                    return;
                }
                List<Long> teamList = list.stream().map(o -> Long.valueOf(o.toString())).collect(Collectors.toList());
                teamMapper.deleteBatchIds(teamList);
                //2.批量删除用户队伍关系表中过期的队伍
                LambdaQueryWrapper<UserTeam> userTeamWrapper = new LambdaQueryWrapper<>();
                userTeamWrapper.in(UserTeam::getTeamId,teamList);
                userTeamMapper.delete(userTeamWrapper);
                log.info("删除过期队伍方法执行完毕……");

            }else{
                log.error("未获取锁……");
            }
        }catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }

    }

}
